package com.pj.wisdomlogistics.mvp.model;


import com.google.gson.Gson;
import com.pj.wisdomlogistics.BuildConfig;
import com.pj.wisdomlogistics.entity.RepairQuestions;
import com.pj.wisdomlogistics.entity.response.BaseResponse;
import com.pj.wisdomlogistics.mvp.frame.MvpModel;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;


public class RepairModel extends MvpModel {

    private static final String POST_URL = BuildConfig.SERVER_HOST + "submitRepairApply.do";

    public Observable<BaseResponse<Double>> submitRepairApply(
            final String userID,
            final String questionIDs,
            final String bespeakStartTime,
            final String bespeakEndTime,
            final String faultPlace,
            final String faultDetail,
            final String remark,
            final List<File> mFiles,
            final String place
    ) {
        return
                Observable.create(new Observable.OnSubscribe<BaseResponse<Double>>() {
                    @Override
                    public void call(Subscriber<? super BaseResponse<Double>> mSubscriber) {
                        PostFormBuilder formBuilder = OkHttpUtils.post().url(POST_URL);

                        formBuilder.addParams("userID", userID);

                        if(mFiles != null){
                            formBuilder.addFiles("mFiles" , mFiles);
                        }

                        formBuilder.addParams("bespeakStartTime", bespeakStartTime);
                        formBuilder.addParams("bespeakEndTime", bespeakEndTime);
                        formBuilder.addParams("faultPlace", faultPlace);
                        formBuilder.addParams("faultDetail", faultDetail);
                        formBuilder.addParams("remark", remark);
                        formBuilder.addParams("questionIDs", questionIDs);
                        formBuilder.addParams("place" , place);


                        try {
                            Response response = formBuilder.build().execute();
                            String str = response.body().string();
                            BaseResponse<Double> postResponse = new Gson().fromJson(str, BaseResponse.class);
                            mSubscriber.onNext(postResponse);
                            mSubscriber.onCompleted();
                        } catch (IOException e) {
                            e.printStackTrace();
                            mSubscriber.onError(e);
                        }
                    }
                });
    }


    public Observable<BaseResponse<List<RepairQuestions>>> findQuestions(){
        return mApiService.findQuestions();
    };
}
